﻿using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using log4net.Layout;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZXing;

namespace Dting_libraries
{
    #region //二进制序列化
    //序列化的位置务必加上[Serializable]
    public class Serialize_Class  
    {
        //序列化方法
        public int Serialize<T>(T source, string file_path)  
        {
            if (!typeof(T).IsSerializable)
            {
                //MessageBox.Show("类型必须是可序列化", "提示");
                return 1;
            }

            if (Object.ReferenceEquals(source, null))
            {
                //MessageBox.Show("实例不是相同的实例", "提示");
                return 2;
            }
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Create))//创建一个文件流，对文件进行写入
                {
                    BinaryFormatter bf = new BinaryFormatter();//使用CLR二进制格式器
                    bf.Serialize(fs, source); //序列化到硬盘
                    fs.Close();//关闭文件流
                }
                return 0;
            }
            catch
            {
                return 3;
            }
        }
        //反序列
        public T Deserialize<T>(string file_path)
        {
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Open))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    return (T)binaryFormatter.Deserialize(fs);
                }
            }
            catch
            {
                return default(T);
            }
        }
        //夸集合反序列
        public T Deserialize2<T>(string file_path)
        {

            using (FileStream fs = new FileStream(file_path, FileMode.Open))
            {
                IFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Binder = new UBinder();
                return (T)binaryFormatter.Deserialize(fs);
            }
        }

        public class UBinder : SerializationBinder
        {
            public override Type BindToType(string assemblyName, string typeName)
            {
                Assembly ass = Assembly.GetExecutingAssembly();
                return ass.GetType(typeName);
            }
        }
    }
    #endregion


    #region  //ini类
    public class ini_Class
    {
        public string _iniPath;  //ini连接路径

        [DllImport("kernel32")]//返回0表示失败，非0为成功
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);


        //构造函数文件路径初始
        public ini_Class(string iniPath)
        {
            _iniPath = Path.GetFullPath(Application.StartupPath + "\\" + iniPath);
            //_iniPath = Path.GetFullPath(iniPath);
        }

        /// <读INI文件>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="NoText"></param>
        /// <文件路径="iniFilePath"></param>
        /// <returns></returns>
        public string Read_Ini(string Section, string Key, string sfc)
        {
            //解析字符
            try
            {
                Key = Key.Replace("\"", "");
                Key = Key.Replace(sfc, "");
            }
            catch (Exception e) {; }

            try
            {
                if (File.Exists(_iniPath))
                {
                    StringBuilder temp = new StringBuilder(1024);
                    GetPrivateProfileString(Section, Key, "", temp, 1024, _iniPath);
                    return temp.ToString();
                }
                else
                {
                    return String.Empty;
                }
            }
            catch (Exception e) { return String.Empty; }

        }
        public string Read_Ini(string Section, string Key)
        {
            //解析字符
            try
            {
                Key = Key.Replace("\"", "");
            }
            catch (Exception e) {; }

            try
            {
                if (File.Exists(_iniPath))
                {
                    StringBuilder temp = new StringBuilder(1024);
                    GetPrivateProfileString(Section, Key, "", temp, 1024, _iniPath);
                    return temp.ToString();
                }
                else
                {
                    return String.Empty;
                }
            }
            catch (Exception e) { return String.Empty; }

        }
        /// <写Ini文件>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <param name="iniFilePath"></param>
        /// <returns></returns>
        public int Write_Ini(string Section, string Key, string Value)
        {
            try
            {
                long OpStation = WritePrivateProfileString(Section, Key, Value, _iniPath);
                if (OpStation == 0)
                { return 0; }
                else
                { return 1; }
            }
            catch (Exception e) { return 1; }
        }

    }
    #endregion


    #region //Log
    public class logicClass
    {
        private ILog log;
        public logicClass(ListBox _ListBox)
        {
            //log4初始化
            string path = Application.StartupPath + "\\log4.config";
            //XmlConfigurator.Configure(new FileInfo(path));//不监控配置文件改变
            XmlConfigurator.ConfigureAndWatch(new FileInfo(path));//监控配置文件改变
            log = LogManager.GetLogger("");

            //初始化log信息同步到界面
            if (_ListBox == null)
                return;
            var LogPattern = "%d [%t] %-4p %c-> %m%n";
            var LogListAppender = new Log4ToListbox();
            LogListAppender.listBox = _ListBox;
            LogListAppender.listBox.HorizontalScrollbar = true;
            LogListAppender.Layout = new PatternLayout(LogPattern);
            BasicConfigurator.Configure(LogListAppender);
        }

        public void Info(string message)
        {
            log.Info(message);
        }

        public void Error(string message)
        {
            log.Error(message);
        }

        public void Debug(string message)
        {
            log.Debug(message);
        }
    }

    class Log4ToListbox : AppenderSkeleton
    {
        public ListBox listBox { get; set; }
        public Log4ToListbox()
        {
            ;
        }
        protected override void Append(LoggingEvent loggingEvent)
        {
            if (loggingEvent == null) return;
            StringWriter writer = new StringWriter();
            this.Layout.Format(writer, loggingEvent);
            Print_listbox(writer.ToString());
        }

        private void Print_listbox(string str)
        {
            //写入List控件
            if (listBox != null)
            {
                if (!listBox.InvokeRequired)
                {
                    //大于500行自动清除
                    if (listBox.Items.Count > 500) { listBox.Items.Clear(); }
                    string[] _str = Regex.Split(str, "> ");
                    if (_str != null && _str.Length >= 2)
                    {
                        listBox.Items.Add(_str[0] + ">");
                        listBox.Items.Add(_str[1]);
                    }

                    //光标跟随
                    listBox.SelectedIndex = listBox.Items.Count - 1;
                    listBox.SelectedItems.Clear();
                }
                else
                {
                    listBox.BeginInvoke((MethodInvoker)delegate
                    {
                        if (!listBox.IsHandleCreated) return;

                        if (listBox.IsDisposed) return;

                        //大于500行自动清除
                        if (listBox.Items.Count > 500) { listBox.Items.Clear(); }
                        string[] _str = Regex.Split(str, "> ");
                        if (_str != null && _str.Length >= 2)
                        {
                            listBox.Items.Add(_str[0] + ">");
                            listBox.Items.Add(_str[1]);
                        }
                        //光标跟随
                        listBox.SelectedIndex = listBox.Items.Count - 1;
                        listBox.SelectedItems.Clear();

                    });

                }
            }
        }

    }

    #endregion


    #region //mySQL
    public class mySql_class
    {
        private MySqlConnection Conn;
        private string ConnString;//连接字符串
        private object _object = new object();

        /// 构造函数 初始化数据库路径并打开数据库  data_name=数据库名称
        public mySql_class(string ip, string port, string user, string password, string data_name)
        {
            try
            {
                //数据库字符连接串口  MultipleActiveResultSets=True
                ConnString = "server=" + ip + ";Uid=" + user + ";password=" + password + ";Database=" + data_name + ";pooling=false; CharSet=utf8; port=" + port + ";";

                //实例化数据库
                Conn = new MySqlConnection(ConnString);

            }
            catch (Exception er) {; }
        }

        /// <summary>
        /// 打开数据链接
        /// </summary>
        /// <returns></returns>
        public int mySql_open()
        {
            try
            {
                //连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                //设置读取超时时间
                var c = new MySqlCommand("set net_write_timeout=99999999;set net_read_timeout=99999999", Conn);
                c.ExecuteNonQuery();

                return 0;
            }
            catch
            { return 1; }
        }

        /// <summary>
        /// 关闭数据链接
        /// </summary>
        public int mySql_Close()
        {
            try
            {
                if (Conn.State == ConnectionState.Open && Conn != null)
                    Conn.Close();

                Conn.Dispose();
                return 0;
            }
            catch
            {
                return 1;
            }
        }

        /// <summary>
        /// 获取数据库整张表格
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <returns></returns>
        public DataTable mySql_View(string TableName)
        {
            DataTable Dt = new DataTable();
            try
            {
                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                //绑定dataGridView

                using (MySqlCommand comm = new MySqlCommand("select * from " + TableName, Conn))
                {
                    MySqlDataAdapter adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = comm;
                    comm.CommandTimeout = 99999999;//设定命令执行时间
                    adapter.Fill(Dt);
                }
                return Dt;
            }
            catch
            { return Dt; }
            //保证程序出现异常后还能继续执行catch之后的程序
            //finally
        }

        /// <summary>
        /// 写入表格
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="add_str"></param>
        /// //格式："insert into [表名] (测试名称,测试名称)values('15','16')"  写入字符
        /// //格式："insert into [表名] (测试名称,测试名称)values(15,16)"      只可以写入数字
        /// <returns>0成功；1失败</returns>
        public int mySql_add(string TableName, string add_str)
        {
            try
            {
                lock (_object)
                {
                    //重新连接数据库
                    if (Conn.State == ConnectionState.Closed)
                        Conn.Open();

                    String sql = "insert into " + TableName + " " + add_str;
                    using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                    {
                        comm.ExecuteNonQuery();
                    }
                }
                return 0;
            }
            catch (Exception e)
            { //MessageBox.Show("添加失败！请检查字符是否正确,是否为空！" + e.ToString(), "err提示！");
                return 1;
            }
        }


        /// <summary>
        /// 删除指定行
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="list_name">字段名</param>
        /// <param name="b">行元素</param>
        /// <returns>0成功；1失败</returns>
        public int mySql_Delete(string TableName, string column_name, string row_name)
        {
            try
            {
                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                //删 
                //sql = "delete from 表名 where ID = 1;"
                String sql = "delete from " + TableName + " where " + column_name + " = '" + row_name + "'";

                using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                {
                    comm.ExecuteNonQuery();
                }
                return 0;
            }
            catch (Exception e)
            { MessageBox.Show("删除失败！请检查字符是否正确,是否为空！" + e.ToString(), "err提示！"); return 1; }
        }

        /// <summary>
        /// 多条件删除
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="Condition"></param>   格式：[0]=字段名 [1]=行元素 [2]=字段名 [3]=行元素
        /// <returns>0成功；1失败</returns>
        public int mySql_Delete(string TableName, string[] Condition)
        {
            try
            {
                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                //删 
                //sql = "delete from 表名 where ID  like '%USA%' and ID  like '%USA%'    或 where Country = 'USA' AND City != 'Seattle';
                String sql = "delete from " + TableName + " where ";
                for (int i = 0; i < (Condition.Length / 2); i++)
                {
                    if (i == Condition.Length / 2 - 1)
                        sql += Condition[i * 2] + " like '%" + Condition[i * 2 + 1] + "%';";
                    else
                        sql += Condition[i * 2] + " like '%" + Condition[i * 2 + 1] + "%' and ";
                }

                using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                {
                    comm.ExecuteNonQuery();
                }
                return 0;
            }
            catch (Exception e)
            { MessageBox.Show("删除失败！请检查字符是否正确,是否为空！" + e.ToString(), "err提示！"); return 1; }
        }


        /// <summary>
        /// 删除表所有数据
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <returns>0成功；1失败</returns>
        public int mySql_DeleteTableAll(string TableName)
        {
            try
            {
                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                //删除表所有数据 
                //sql = "delete from 表名 where ID = 1;"
                String sql = "truncate table " + TableName + ";";

                using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                {
                    comm.ExecuteNonQuery();
                }

                return 0;
            }
            catch (Exception e)
            { MessageBox.Show("删除失败！请检查字符是否正确,是否为空！" + e.ToString(), "err提示！"); return 1; }
        }

        /// <summary>
        /// 指定更新数据库某行
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="column_name">指定要更新的第一个字段名</param>
        /// <param name="row_name">指定要更新的第一个行名</param>
        /// <param name="update_value">要更新所有的行的值格式："字段名=‘avlue’"</param>
        /// <returns>0成功；1失败</returns>
        public int mySql_Update(string TableName, string column_name, string row_name, string update_value)
        {
            try
            {
                lock (_object)
                {
                    //打开数据库
                    if (Conn.State == ConnectionState.Closed)
                        Conn.Open();

                    //更新数据库 
                    // sql = "UPDATE 表名  SET  字段名=‘avlue’ where ID = 1;"
                    String sql = "UPDATE " + TableName + " SET " + update_value + " where " + column_name + " = '" + row_name + "'";

                    using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                    {
                        comm.ExecuteNonQuery();
                    }
                    return 0;
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show("更新失败！请检查字符是否正确,是否为空！" + e.ToString(), "err提示！"); 
                return 1;
            }
        }

        /// <summary>
        ///  指定更新数据库某行 多个条件更新
        /// </summary>
        /// <param name="TableName">表名</param></param>
        /// <param name="Condition">条件多个方式写入，参数一：字段名，参数二：字段参数 </param>   （参数一：字段名，参数二：字段参数，参数三：字段名，参数四：字段参数）
        /// <param name="update_value">要更新所有的行的值格式："字段名=‘avlue’"</param>
        /// <returns>0成功；1失败</returns>
        public int mySql_Update(string TableName, string[] Condition, string update_value)
        {
            try
            {
                lock (_object)
                {
                    //打开数据库
                    if (Conn.State == ConnectionState.Closed)
                        Conn.Open();

                    //更新数据库 
                    // sql = "UPDATE 表名  SET  字段名=‘avlue’ where ID = 1;"
                    String sql = "UPDATE " + TableName + " SET " + update_value + " where ";

                    for (int i = 0; i < (Condition.Length / 2); i++)
                    {
                        if (i == Condition.Length / 2 - 1)
                            sql += Condition[i * 2] + " like '%" + Condition[i * 2 + 1] + "%';";
                        else
                            sql += Condition[i * 2] + " like '%" + Condition[i * 2 + 1] + "%' and ";
                    }

                    using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                    {
                        comm.ExecuteNonQuery();
                    }
                    return 0;
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show("更新失败！请检查字符是否正确,是否为空！" + e.ToString(), "err提示！");
                return 1;
            }
        }

        /// <summary>
        /// 获取数据库表的字段名
        /// </summary>
        /// <param name="MysqlName"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public string[] MysqlField_Seek(string MysqlName, string TableName)
        {
            lock (_object)
            {
                DataTable Dt = new DataTable();
                int a = Get_NameList(TableName);
                if (a <= 0) return null;
                string[] list_Data = new string[a];
                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                //查询
                string sql = "SELECT column_name  from information_schema.columns where table_name = '" + TableName + "' and table_schema = '" + MysqlName + "' ORDER BY ORDINAL_POSITION asc;";

                using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                {

                    MySqlDataReader reader = comm.ExecuteReader();
                    try
                    {
                        int h = 0;
                        while (reader.Read())
                        {
                            list_Data[h] = reader[0].ToString();
                            h++;
                        }
                        reader.Close();
                        reader.Dispose();
                    }
                    catch
                    {
                        reader.Close();
                        reader.Dispose();
                        list_Data = null;
                    }
                }
                return list_Data;
            }

        }

        /// <summary>
        /// 查询一行字段内容
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="list_name">列名</param>
        /// <param name="b">列名内容</param>
        /// <returns></returns>
        public string[] Mysqllist_Seek(string TableName, string column_name, string row_name)
        {
            try
            {
                lock (_object)
                {
                    int a = Get_NameList(TableName);
                    if (a <= 0) return null;
                    string[] list_Data = new string[a];
                    //重新连接数据库
                    if (Conn.State == ConnectionState.Closed)
                        Conn.Open();

                    //查询
                    string sql = "SELECT * from " + TableName + " where " + column_name + "='" + row_name + "'";

                    using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                    {
                        MySqlDataReader reader = comm.ExecuteReader();
                        reader.Read();
                        try
                        {
                            for (int i = 0; i < a; i++)
                            {
                                list_Data[i] = reader[i].ToString();
                            }
                            reader.Close();
                            reader.Dispose();
                        }
                        catch
                        {
                            reader.Close();
                            reader.Dispose();
                            list_Data = null;
                        }
                    }
                    return list_Data;
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show(Convert.ToString(e), "err提示！");
                return null;
            }
        }

        public string[] Mysqllist_Seek3(string TableName, string column_name, string row_name, string column_name2, string row_name2)
        {
            try
            {
                lock (_object)
                {
                    int a = Get_NameList(TableName);
                    if (a <= 0) return null;
                    string[] list_Data = new string[a];
                    //重新连接数据库
                    if (Conn.State == ConnectionState.Closed)
                        Conn.Open();

                    //查询
                    string sql = "SELECT * from " + TableName + " where " + column_name + " = '" + row_name + "' AND " + column_name2 + " = '" + row_name2 + "'";

                    using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                    {
                        MySqlDataReader reader = comm.ExecuteReader();
                        reader.Read();
                        try
                        {
                            for (int i = 0; i < a; i++)
                            {
                                list_Data[i] = reader[i].ToString();
                            }
                            reader.Close();
                            reader.Dispose();
                        }
                        catch
                        {
                            reader.Close();
                            reader.Dispose();
                            list_Data = null;
                        }
                    }
                    return list_Data;
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show(Convert.ToString(e), "err提示！");
                return null;
            }
        }

        public string Mysqllist_Seek2(string TableName, string column_name, string row_name, string column_bar)
        {
            try
            {
                lock (_object)
                {
                    string _column = "";
                    //重新连接数据库
                    if (Conn.State == ConnectionState.Closed)
                        Conn.Open();

                    //查询
                    string sql = "SELECT * from " + TableName + " where " + column_name + "='" + row_name + "'";

                    using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                    {
                        MySqlDataReader reader = comm.ExecuteReader();
                        try
                        {
                            if (reader.Read())
                            {
                                ;
                                int index = reader.GetOrdinal(column_bar);
                                _column = reader[index].ToString();

                            }

                            reader.Close();
                            reader.Dispose();
                        }
                        catch
                        {
                            reader.Close();
                            reader.Dispose();
                            _column = "";
                        }
                    }
                    return _column;
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show(Convert.ToString(e), "err提示！");
                return "";
            }
        }

        /// <summary>
        /// 时间段方式搜索
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="list_timer">时间字段名</param>
        /// <param name="start_date">开始时间</param>
        /// <param name="end_date">结束时间</param>
        /// <returns></returns>
        public DataTable MysqlDate_seek(string TableName, string Time_FieldName, string start_date, string end_date)
        {
            DataTable Dt = new DataTable();
            try
            {

                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();
                string sql = "select * from " + TableName + " where ";
                sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                   Convert.ToString(end_date) + "';";

                using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                {
                    MySqlDataAdapter adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = comm;
                    adapter.Fill(Dt);
                }

                return Dt;
            }
            catch (Exception e)
            { MessageBox.Show(Convert.ToString(e), "err提示！"); return Dt = null; }
        }

        /// <summary>
        /// 时间段与多条件方式搜索
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="list_timer">时间字段名</param>
        /// <param name="other">其它条件列字段名，行字段内容</param>
        /// <param name="start_date">开始时间 到秒</param>
        /// <param name="end_date">结束时间 到秒</param>
        /// <returns>搜索结果 表格式</returns>
        public DataTable MysqlDate_seek(string TableName, string Time_FieldName, string[] other, string start_date, string end_date)
        {
            DataTable Dt = new DataTable();
            try
            {

                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();
                string sql = "select * from " + TableName + " where ";
                string _sql = "";

                //按月搜索
                //DateTime date_a = Convert.ToDateTime(end_date.ToString());
                //DateTime d = new DateTime(date_a.Year, date_a.Month, 1);
                //d = d.AddMonths(1).AddDays(-1);
                //String a = d.ToString("yyyy-MM-dd");//读取当月最后一天

                //sql = sql + "Data_timer between '" + Convert.ToString(start_date.ToString()) + "-01 00:00:00' AND '" +
                //                                     a + " 23:59:59'";

                //按天搜索
                if (other.Length > 0)
                {
                    for (int i = 0; i < (other.Length / 2); i++)
                    {
                        if (i == other.Length / 2 - 1)
                            _sql += other[i * 2] + " like '%" + other[i * 2 + 1] + "%' ";
                        else
                            _sql += other[i * 2] + " like '%" + other[i * 2 + 1] + "%' AND ";
                    }
                    sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                         Convert.ToString(end_date) + "' AND " + _sql + "; ";
                }
                else
                {
                    sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                         Convert.ToString(end_date) + "'; ";
                }

                using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                {
                    MySqlDataAdapter adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = comm;
                    adapter.Fill(Dt);
                }

                return Dt;
            }
            catch (Exception e)
            { MessageBox.Show(Convert.ToString(e), "err提示！"); return Dt = null; }
        }

        /// <summary>
        /// 时间段与多字段与，多条件或方式搜索  定制
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="list_timer"></param>
        /// <param name="Mobile_SN"></param>
        /// <param name="otherA"></param>
        /// <param name="otherB"></param>
        /// <param name="start_date"></param>
        /// <param name="end_date"></param>
        /// <returns></returns>
        public DataTable MysqlDate_seekA(string TableName, string Time_FieldName, string[] Mobile_SN, string[] otherA, string[] otherB, string start_date, string end_date)
        {
            DataTable Dt = new DataTable();
            try
            {

                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();
                string sql = "select * from " + TableName + " where ";
                string a_sql = "";
                string b_sql = "";

                //按月搜索
                //DateTime date_a = Convert.ToDateTime(end_date.ToString());
                //DateTime d = new DateTime(date_a.Year, date_a.Month, 1);
                //d = d.AddMonths(1).AddDays(-1);
                //String a = d.ToString("yyyy-MM-dd");//读取当月最后一天

                //sql = sql + "Data_timer between '" + Convert.ToString(start_date.ToString()) + "-01 00:00:00' AND '" +
                //                                     a + " 23:59:59'";

                //按天搜索
                if (otherA.Length > 1)
                {
                    //字段1
                    sql = "select * from " + TableName + " where ";
                    a_sql = "";
                    b_sql = "";
                    for (int i = 0; i < (otherA.Length / 2); i++)
                    {
                        if (i == otherA.Length / 2 - 1)
                            a_sql += otherA[i * 2] + " like '%" + otherA[i * 2 + 1] + "%' ";
                        else
                            a_sql += otherA[i * 2] + " like '%" + otherA[i * 2 + 1] + "%' OR ";
                    }
                    if (Mobile_SN.Length > 1)
                    {
                        sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                         Convert.ToString(end_date) + "' AND " + Mobile_SN[0] + " like '%" + Mobile_SN[1] + "%' AND " + a_sql + "; ";
                    }
                    else
                    {
                        sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                                                 Convert.ToString(end_date) + "' AND " + a_sql + "; ";
                    }
                }

                if (otherB.Length > 1)
                {
                    //字段2
                    sql = "select * from " + TableName + " where ";
                    a_sql = "";
                    b_sql = "";
                    for (int i = 0; i < (otherB.Length / 2); i++)
                    {
                        if (i == otherB.Length / 2 - 1)
                            a_sql += otherB[i * 2] + " like '%" + otherB[i * 2 + 1] + "%' ";
                        else
                            a_sql += otherB[i * 2] + " like '%" + otherB[i * 2 + 1] + "%' OR ";
                    }
                    if (Mobile_SN.Length > 1)
                    {
                        sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                         Convert.ToString(end_date) + "' AND " + Mobile_SN[0] + " like '%" + Mobile_SN[1] + "%' AND " + a_sql + "; ";
                    }
                    else
                    {
                        sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                                                 Convert.ToString(end_date) + "' AND " + a_sql + "; ";
                    }
                }


                if (otherA.Length > 1 && otherB.Length > 1)
                {
                    //字段1
                    sql = "select * from " + TableName + " where ";
                    a_sql = "";
                    b_sql = "";

                    for (int i = 0; i < (otherA.Length / 2 - 0); i++)
                    {
                        if (i == otherA.Length / 2 - 1)
                            a_sql += otherA[(i + 0) * 2] + " like '%" + otherA[(i + 0) * 2 + 1] + "%' ";
                        else
                            a_sql += otherA[(i + 0) * 2] + " like '%" + otherA[(i + 0) * 2 + 1] + "%' OR ";
                    }
                    //字段2
                    for (int i = 0; i < (otherB.Length / 2 - 0); i++)
                    {
                        if (i == otherB.Length / 2 - 1)
                            b_sql += otherB[(i + 0) * 2] + " like '%" + otherB[(i + 0) * 2 + 1] + "%' ";
                        else
                            b_sql += otherB[(i + 0) * 2] + " like '%" + otherB[(i + 0) * 2 + 1] + "%' OR ";
                    }

                    if (Mobile_SN.Length > 1)
                    {
                        sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                         Convert.ToString(end_date) + "' AND  " + Mobile_SN[0] + " like '%" + Mobile_SN[1] + "%' AND (" + a_sql + ") AND (" + b_sql + "); ";
                    }
                    else
                    {
                        sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                         Convert.ToString(end_date) + "' AND (" + a_sql + ") AND (" + b_sql + "); ";
                    }
                }
                else if (otherA.Length <= 1 && otherB.Length <= 1)
                {
                    if (Mobile_SN.Length > 1)
                    {
                        sql = "select * from " + TableName + " where ";
                        sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                             Convert.ToString(end_date) + "' AND " + Mobile_SN[0] + " like '%" + Mobile_SN[1] + "%';";
                    }
                    else
                    {
                        sql = "select * from " + TableName + " where ";
                        sql += Time_FieldName + " between '" + Convert.ToString(start_date) + "' AND '" +
                                                             Convert.ToString(end_date) + "'; ";

                    }
                }

                using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                {
                    MySqlDataAdapter adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = comm;
                    adapter.Fill(Dt);
                }

                return Dt;
            }
            catch (Exception e)
            { MessageBox.Show(Convert.ToString(e), "err提示！"); return Dt = null; }
        }

        /// <summary>
        /// 多个条件搜索
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="Condition">条件多个方式写入，参数一：字段名，参数二：字段参数 ~~</param> （参数一：字段名，参数二：字段参数，参数三：字段名，参数四：字段参数）
        /// <returns></returns>
        public DataTable MysqlCondition_seek(string TableName, string[] Condition)
        {
            DataTable Dt = new DataTable();
            string[] str_buf;
            try
            {
                if (Condition.Length >= 2)
                    str_buf = new string[Condition.Length];
                else
                    return Dt = null;


                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();
                string sql = "select * from " + TableName + " where ";

                for (int i = 0; i < (Condition.Length / 2); i++)
                {
                    if (i == Condition.Length / 2 - 1)
                        sql += Condition[i * 2] + " like '%" + Condition[i * 2 + 1] + "%';";
                    else
                        sql += Condition[i * 2] + " like '%" + Condition[i * 2 + 1] + "%' and ";
                }

                using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                {
                    MySqlDataAdapter adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = comm;
                    adapter.Fill(Dt);
                }

                return Dt;
            }
            catch (Exception e)
            { MessageBox.Show(Convert.ToString(e), "err提示！"); return Dt = null; }
        }

        /// <summary>
        /// 多条件获取指定重复记录中最近的数据
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Condition"></param>
        /// <returns></returns>
        private string[] Mysqllist_SeekA(string TableName, string[] Condition)
        {
            string[] Dt;
            try
            {
                string _sql = "";
                for (int i = 0; i < (Condition.Length / 2); i++)
                {
                    if (i == Condition.Length / 2 - 1)
                        _sql += Condition[i * 2] + " like '%" + Condition[i * 2 + 1] + "%';";
                    else
                        _sql += Condition[i * 2] + " like '%" + Condition[i * 2 + 1] + "%' AND ";
                }

                string sql = "SELECT sign.* FROM " + TableName + " sign WHERE NOT exists(SELECT 1 FROM " + TableName +
                              "  WHERE  Mobile_SN = sign.Mobile_SN AND MobileCame_ID = sign.MobileCame_ID AND Testitem_name = sign.Testitem_name AND sign.Date_timer < Date_timer)  AND " +
                              Condition[0] + " like '%" + Condition[1] + "%' " +
                             "AND " + _sql +
                             "ORDER BY Date_timer DESC";

                using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                {
                    //MySqlDataAdapter adapter = new MySqlDataAdapter();
                    //adapter.SelectCommand = comm;
                    //adapter.Fill(Dt);

                    MySqlDataReader reader = comm.ExecuteReader();
                    reader.Read();
                    Dt = new string[reader.FieldCount];
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        Dt[i] = reader[i].ToString();
                    }
                    comm.Dispose();
                }
                return Dt;
            }
            catch (Exception ex)
            { return Dt = null; }
            //{ MessageBox.Show(Convert.ToString(e), "err提示！"); return Dt = null; }
        }

        /// <summary>
        /// 返回字段名的个数
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <returns>0:失败</returns>
        public int Get_NameList(string TableName)
        {
            int a = 0;

            try
            {
                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                using (MySqlCommand comm = new MySqlCommand("select * from " + TableName, Conn))
                {
                    MySqlDataReader dr = comm.ExecuteReader();
                    a = dr.FieldCount;
                    dr.Close();
                    dr.Dispose();
                }

                return a;
            }
            catch (Exception e)
            {
                //MessageBox.Show(Convert.ToString(e), "err提示！");
                return 0;
            }
        }

        /// <summary>
        /// 获取数据库表的总记录数
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <returns>0:失败  大于0：成功</returns>
        public int MysqlData_Count(string TableName)
        {
            int b;
            try
            {
                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                //读取数据库表的总记录数
                String sql = "select count(*) from " + TableName;
                using (MySqlCommand comm = new MySqlCommand(sql, Conn))
                {
                    b = Convert.ToInt32(comm.ExecuteScalar());
                }

                return b;
            }
            catch (Exception e)
            { MessageBox.Show(Convert.ToString(e), "err提示！"); return 0; }
        }

        /// <summary>
        /// 保存DataGridView到Access
        /// </summary>
        /// <param name="te">DataGridView控件</param>
        /// <param name="TableName">表名</param>
        /// <returns>0:成功 1：失败</returns>
        public Boolean View_MysqlData(DataGridView te, string TableName)
        {
            try
            {
                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                te.EndEdit();
                String sql = "select * from " + TableName;
                MySqlDataAdapter da = new MySqlDataAdapter(sql, Conn);
                MySqlCommandBuilder bld = new MySqlCommandBuilder(da);
                da.UpdateCommand = bld.GetUpdateCommand();

                //把DataGridView赋值给dataTbale。(DataTable)的意思是类型转换，前提是后面紧跟着的东西要能转换成dataTable类型
                DataTable dt = (DataTable)te.DataSource;
                da.Update(dt);
                dt.AcceptChanges();
                //Conn.Close();
                return true;
            }
            catch (Exception e)
            { MessageBox.Show(Convert.ToString(e), "err提示！"); return false; }
        }

        /// <summary>
        /// 保存DataTable到mysql
        /// </summary>
        /// <param name="te"></param>
        /// <param name="TableName"></param>
        /// <param name="message_str"></param>
        /// <returns>true成功；false失败</returns>
        public int Table_MysqlData(DataTable te, string TableName, ref string message_str)
        {

            try
            {
                te.TableName = TableName;
                string result = string.Empty;
                if (null == te || te.Rows.Count <= 0)
                {
                    message_str = "添加失败！DataTable暂无数据！";
                    return 1;
                }
                if (string.IsNullOrEmpty(te.TableName))
                {
                    message_str = "添加失败！请先设置DataTable的名称！";
                    return 2;
                }

                // 构建INSERT语句
                StringBuilder sb = new StringBuilder();
                sb.Append("INSERT INTO " + te.TableName + "(");
                for (int i = 1; i < te.Columns.Count; i++)
                {
                    sb.Append(te.Columns[i].ColumnName + ",");
                }
                sb.Remove(sb.ToString().LastIndexOf(','), 1);
                sb.Append(") VALUES ");
                for (int i = 1; i < te.Rows.Count; i++)
                {
                    sb.Append("(");
                    for (int j = 1; j < te.Columns.Count; j++)
                    {
                        sb.Append("'" + te.Rows[i][j] + "',");
                    }
                    sb.Remove(sb.ToString().LastIndexOf(','), 1);
                    sb.Append("),");
                }
                sb.Remove(sb.ToString().LastIndexOf(','), 1);
                sb.Append(";");

                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                int res = -1;
                using (MySqlCommand cmd = new MySqlCommand(sb.ToString(), Conn))
                {
                    try
                    {
                        if (cmd.ExecuteNonQuery() > 0)
                            message_str = "OK";
                    }
                    catch (Exception ex)
                    {
                        // Unknown column 'names' in 'field list' 
                        message_str = "NG 操作失败！" + ex.Message.Replace("Unknown column", "未知列").Replace("in 'field list'", "存在字段集合中！");
                        return 3;
                    }
                }
                return 0;
            }
            catch
            { return 4; }
        }

        /// <summary>
        /// mysql 不支持
        /// </summary>
        /// <param name="te"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public string Table_MysqlData1(DataTable te, string TableName)
        {

            try
            {
                te.TableName = TableName;
                string result = string.Empty;
                if (null == te || te.Rows.Count <= 0)
                {
                    return "添加失败！DataTable暂无数据！";
                }
                if (string.IsNullOrEmpty(te.TableName))
                {
                    return "添加失败！请先设置DataTable的名称！";
                }


                //重新连接数据库
                if (Conn.State == ConnectionState.Closed)
                    Conn.Open();

                String sql = "select * from " + TableName;

                using (MySqlCommand cmd = new MySqlCommand(sql, Conn))
                {
                    try
                    {
                        MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                        MySqlCommandBuilder builder = new MySqlCommandBuilder(adapter);
                        adapter.UpdateCommand = builder.GetUpdateCommand();

                        DataTable temp = new DataTable();
                        adapter.Fill(temp);
                        temp = te;
                        adapter.Update(temp.GetChanges());
                        temp.AcceptChanges();
                        return "OK";
                    }
                    catch (Exception ex)
                    {
                        // Unknown column 'names' in 'field list' 
                        result = "操作失败！" + ex.Message.Replace("Unknown column", "未知列").Replace("in 'field list'", "存在字段集合中！");
                        return "NG " + result;
                    }
                }
            }
            catch
            { return "NG"; }
        }

        /// <summary>
        /// DataTable表数据显示到DataGridview 必须要有列名并与DataTable对齐
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="dataGridView">DataGridView</param>
        /// <returns>true成功；false失败</returns>
        public int GridviewShowDataTable(DataTable table, DataGridView dataGridView)
        {
            try
            {
                if (table.Rows.Count > 0)
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        dataGridView.Rows.Add();
                        dataGridView.Rows[i].Cells[0].Value = i;
                        for (int j = 0; j < (table.Columns.Count - 1); j++)
                        {
                            dataGridView.Rows[i].Cells[j + 1].Value = table.Rows[i].ItemArray[j + 1].ToString();
                            //Application.DoEvents();//可以交出控制权但是慢
                        }
                    }
                }

                return 0;
            }
            catch (Exception ex)
            { return 1; }

        }

        /// <summary>
        /// 获取DataTable列名
        /// </summary>
        /// <param name="table"></param>
        /// <param name="columunName"></param>
        /// <returns></returns>
        public string[] GetDataTable_columuName(DataTable table)
        {
            try
            {
                string[] columunName = null;
                if (table.Columns.Count > 0)
                {
                    int columnNum = 0;
                    columnNum = table.Columns.Count;
                    columunName = new string[columnNum - 1];
                    for (int i = 1; i < table.Columns.Count; i++)
                    {
                        columunName[i - 1] = table.Columns[i].ColumnName;
                    }
                }
                return columunName;
            }
            catch
            { return null; }

        }


        /// <summary>
        /// DataGridView导出为Datatable
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <returns>Datatable</returns>
        public DataTable GetDataGridView(DataGridView dgv)
        {
            DataTable dt = new DataTable();

            // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText.ToString());
                dt.Columns.Add(dc);
            }

            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }


    }
    #endregion


    #region //生成条码与二维码
    public class User_barcode
    {
        /// <summary>
        /// 生成条码与二维码
        /// </summary>
        /// <param name="barcode_info">条码信息</param>
        /// <param name="barcode_byte">条码类型</param>
        /// <param name="Height">条码高度</param>
        /// <param name="Width">条码宽度</param>
        /// <returns></returns>
        public Bitmap Create_Barcode(string barcode_info, BarcodeFormat barcode_byte = BarcodeFormat.QR_CODE, int Width = 200, int Height = 200)
        {
            try
            {
                if (barcode_info == string.Empty) return null;

                // 1.设置QR二维码的规格
                ZXing.QrCode.QrCodeEncodingOptions qrEncodeOption = new ZXing.QrCode.QrCodeEncodingOptions();
                qrEncodeOption.CharacterSet = "UTF-8"; // 设置编码格式，否则读取'中文'乱码
                qrEncodeOption.Height = Height;
                qrEncodeOption.Width = Width;
                qrEncodeOption.Margin = 0; // 设置周围空白边距
                qrEncodeOption.NoPadding = false;
                qrEncodeOption.ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.M;
                qrEncodeOption.PureBarcode = false;//紧输出条码

                // 2.生成条形码图片并保存
                BarcodeWriter wr = new BarcodeWriter();
                wr.Format = barcode_byte; // 二维码
                wr.Options = qrEncodeOption;
                return wr.Write(barcode_info);
            }
            catch (Exception er)
            {
                return null;
            }
        }

        private Image GetBarcodeImage(Image buf_Image, string str, int width, int Height)
        {
            var bmp = new Bitmap(width, Height, PixelFormat.Format32bppArgb);
            using (var g = Graphics.FromImage(bmp))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                g.Clear(Color.Transparent);

                using (var p = new Pen(Color.FromArgb(151, 156, 158), 2f))
                {
                    g.FillRectangle(Brushes.White, new Rectangle(0, 0, width, Height));
                    g.DrawImage(buf_Image, (width - buf_Image.Width) / 2, (Height - buf_Image.Height) / 2);

                    //设置打印内容及其字体，颜色和位置
                    //g.DrawString(str, new Font(new FontFamily("黑体"), 24), System.Drawing.Brushes.Black, 50, 50); 

                }
            }
            return bmp;
        }




        #region//打印
        public class User_Print
        {
            Image buf = null;
            //实例化打印对象
            PrintDocument printDocument1 = new PrintDocument();

            public void Printer(Image img)
            {
                buf = img;

                //指定打印机
                printDocument1.PrinterSettings.PrinterName = "Microsoft Print to PDF";
                //设置页边距
                printDocument1.PrinterSettings.DefaultPageSettings.Margins.Left = 0;
                printDocument1.PrinterSettings.DefaultPageSettings.Margins.Top = 0;
                printDocument1.PrinterSettings.DefaultPageSettings.Margins.Right = 0;
                printDocument1.PrinterSettings.DefaultPageSettings.Margins.Bottom = 0;
                //设置尺寸大小，如不设置默认是A4纸
                //A4纸的尺寸是210mm×297mm，
                //当你设定的分辨率是72像素/英寸时，A4纸的尺寸的图像的像素是595×842
                //当你设定的分辨率是150像素/英寸时，A4纸的尺寸的图像的像素是1240×1754
                //当你设定的分辨率是300像素/英寸时，A4纸的尺寸的图像的像素是2479×3508，
                //printDocument1.DefaultPageSettings.PaperSize = new PaperSize("A4", 595, 842);

                //设置打印用的纸张,当设置为Custom的时候，可以自定义纸张的大小
                printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custum", 500, 500);

                //是否打印到文件开启或关闭
                printDocument1.PrinterSettings.PrintToFile = true;
                printDocument1.PrinterSettings.PrintFileName = Application.StartupPath + @"\dl.pdf";

                //注册PrintPage事件，打印每一页时会触发该事件
                printDocument1.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);

                //初始化打印预览对话框对象
                PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
                //将printDocument1对象赋值给打印预览对话框的Document属性
                printPreviewDialog1.Document = printDocument1;

                //打开打印预览对话框
                DialogResult result = printPreviewDialog1.ShowDialog();
                try
                {
                    if (result == DialogResult.OK)
                        printDocument1.Print();//开始打印
                }
                catch (InvalidPrinterException er)
                {
                    ;
                }
                finally
                {
                    printDocument1.Dispose();
                }

            }
            private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
            {
                //设置打印内容及其字体，颜色和位置
                //e.Graphics.DrawString("Hello World！", new Font(new FontFamily("黑体"), 24), System.Drawing.Brushes.Red, 50, 50);

                e.Graphics.DrawImage(buf, 50, 100);
            }

            //
            public string[] GetPrinterDevice()
            {
                try
                {
                    List<string> PrintS = new List<string>();
                    foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称
                    {
                        PrintS.Add(sPrint);
                    }
                    return PrintS.ToArray();
                }
                catch { return null; }
            }



        }
        #endregion
    }
    #endregion

}
